<?php
namespace app\controllers;

use app\award\C;
use app\award\Profit;
use app\models\MonthProfit;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\Queue;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\models\UserBalance;
use app\models\ZSetting;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class MonthController extends Controller
{
    protected $set;

    /*
     * 每月1号 3点
     * 0 3 1 * * /usr/bin/curl https://jj2024-api.97app.cn/month/repeat
     * 0 4 1 * * /usr/bin/curl https://jj2024-api.97app.cn/month/div
     * 0 5 1 * * /usr/bin/curl https://jj2024-api.97app.cn/month/sum
     *
     *
     * 0 3 1 * * /usr/bin/curl http://api.derris.cn/month/repeat
     */

    // public function actionRepeatOld()
    // {
    //     var_dump(1);exit;
    //
    //     $transaction = \Yii::$app->db->beginTransaction();
    //
    //     $this->set = SetUserUp::getLastOne();
    //
    //     try {
    //
    //         $done = UserCommission::find()
    //             ->where(['award_type' => 101])
    //             ->andWhere(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
    //             ->one();
    //         if ($done) {
    //             echo '本月已经分红了,请勿重复操作';
    //             return;
    //         }
    //
    //         $orders = Order::find()
    //             ->where(['is_repeat' => 1])
    //             // 上个月的
    //             ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
    //             // 云仓提货不算
    //             ->andWhere(['is_extract' => 0])
    //             ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
    //             ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
    //             ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
    //             ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
    //             ->select(['id', 'total_pay', 'total_freight'])
    //             ->asArray()
    //             ->all();
    //
    //         // var_dump($orders);exit;
    //
    //         $sum = 0;
    //         foreach ($orders as $order) {
    //             $sum += $order['total_pay'] - $order['total_freight'];
    //         }
    //         $sum = $sum * $this->set->p1 / 100;
    //
    //         // 需要平分的人
    //         $users = User::find()
    //             ->where(['>', 'c1', 0])
    //             ->orWhere(['>', 'c2', 0])
    //             ->select(['id'])
    //             ->asArray()
    //             ->all();
    //
    //         // var_dump($users);exit;
    //
    //         if ($users) {
    //             $commission = $sum / count($users);
    //             foreach ($users as $user) {
    //                 $this->saveCommission($user['id'], $commission, 101, '复购分红');
    //             }
    //         }
    //
    //         $transaction->commit();
    //     } catch (\Exception $e) {
    //         $transaction->rollBack();
    //     }
    // }

    // 复购现在按这个来
    // 复购分红
    // 这个是戴瑞琛的团队分红奖
    // 累计的
    // 扣除之前提的
    // 0 3 1 * * /usr/bin/curl http://api.derris.cn/month/repeat
    public function actionRepeat()
    {
        // var_dump(1);exit;

        $transaction = \Yii::$app->db->beginTransaction();

        $this->set = SetUserUp::getLastOne();

        try {

            // 查询本月分红
            // $has = UserCommission::find()
            //     ->where(['award_type' => 123])
            //     ->andWhere(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
            //     ->one();
            $has = MonthProfit::find()
                ->where(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
                ->one();
            if ($has) {
                echo '本月已经分红了,请勿重复操作';
                return;
            }

            // 2) 计算分红
            $list = Profit::getList();

            // var_dump($list);exit;

            foreach ($list as $user) {
                if (!isset($user['real_amount']) || $user['amount'] == 0) {
                    continue;
                }

                $this->saveCommission2($user, $user['id'], $user['real_amount'], 123, '月团队奖');
            }

            $transaction->commit();
        } catch (\Exception $e) {
            var_dump($e->getMessage(), $e->getLine(), $e->getFile());
            $transaction->rollBack();
        }
    }

    /*
     * 每月1号 5点
     * 0 5 1 * * /usr/bin/curl http://api.derris.cn/month/div
     */
    // 分红
    public function actionDiv()
    {
        $transaction = \Yii::$app->db->beginTransaction();

        $this->set = SetUserUp::getLastOne();

        try {

            $done = UserCommission::find()
                ->where(['award_type' => [102, 103]])
                ->andWhere(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
                ->one();
            if ($done) {
                echo '本月已经分红了,请勿重复操作';
                return;
            }

            $orders = Order::find()
                // 不是云仓提货的
                ->where(['is_extract' => 0])
                // 上个月的
                ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
                ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
                ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
                ->select(['id', 'total_pay', 'total_freight'])
                ->asArray()
                ->all();

            // var_dump($orders);exit;

            $sum = 0;
            foreach ($orders as $order) {
                $sum += $order['total_pay'] - $order['total_freight'];
            }

            // 需要平分的人
            $users = User::find()
                ->where(['>', 'c1', 0])
                ->orWhere(['>', 'c2', 0])
                ->select(['id'])
                ->asArray()
                ->all();

            // var_dump($users);exit;

            if ($users) {

                // 分红
                $commission = ($sum * $this->set->p2 / 100) / count($users);

                // 总业绩
                $total = 0;
                // 需要重新生成数组
                $data = [];
                foreach ($users as $user) {
                    $this->saveCommission($user['id'], $commission, 102, '分红');

                    // 计算业绩
                    $score = $this->getScore($user['id']);
                    $total += $score;
                    $data[] = [
                        'id' => $user['id'],
                        'score' => $score
                    ];
                }

                // 加权分红
                $commission = $sum * $this->set->p3 / 100;
                foreach ($data as $item) {
                    $ratio = $item['score'] / $total;
                    $this->saveCommission($item['id'], $commission * $ratio, 103, '加权分红');
                }
            }

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
        }
    }

    // 股东结算
    public function actionSum()
    {
        $transaction = \Yii::$app->db->beginTransaction();

        $this->set = SetUserUp::getLastOne();

        try {

            $done = UserCommission::find()
                ->where(['award_type' => [104, 105]])
                // ->andWhere(['DATE_FORMAT(create_time, "%Y-%m")' => date('Y-m')])
                ->one();
            if ($done) {
                echo '本月已经分红了,请勿重复操作';
                return;
            }

            $orders = Order::find()
                // 上个月的
                ->where("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
                // 云仓提货不算
                ->andWhere(['is_extract' => 0])
                ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
                ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
                ->select(['id', 'total_pay', 'total_freight', 'is_repeat'])
                ->asArray()
                ->all();

            // var_dump($orders);exit;

            $sum = 0;
            foreach ($orders as $order) {
                $sum += $order['total_pay'] - $order['total_freight'];
            }

            // 德悦
            $user_id = User::find()
                ->where(['>', 'c3', 0])
                ->select(['id'])
                ->scalar();
            if ($user_id) {
                $this->saveCommission($user_id, $sum * $this->set->g1 / 100, 104, '股东结算');
            }

            // 股东平分
            $users = User::find()
                ->where(['>', 'c4', 0])
                ->select(['id'])
                ->asArray()
                ->all();
            if ($users) {

                // 利润=产品金额- 总拨比-产品成本
                $ratio = $this->set->g1 + $this->set->p3 + $this->set->p2;
                $x = $sum - $sum * $ratio / 100;

                // 计算成本 拨比
                $total = 0;
                foreach ($orders as $order) {
                    $amount = $order['total_pay'] - $order['total_freight'];

                    // 去掉分红比例
                    // 复购产品, 增加一个分红比例
                    if ($order['is_repeat']) {
                        $amount -= ($ratio + $this->set->p1) * $amount / 100;
                    } else {
                        $amount -= $ratio * $amount / 100;
                    }

                    // 去掉佣金
                    $total_commission = (float)UserCommission::find()
                        ->where(['order_id' => $order['id']])
                        ->sum('balance');
                    $total -= $total_commission;

                    // 产品成本
                    // 没有填写成本的, 不计算为总收入
                    $cost = $this->getProduct($order['id']);
                    if ($cost > 0) {
                        $amount -= $cost;
                        $total += $amount;
                    }

                }

                // var_dump($total);exit;

                foreach ($users as $user) {
                    $this->saveCommission($user['id'], $total / count($users), 105, '股东利润');
                }
            }

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
        }
    }

    // 产品成本
    private function getProduct($order_id)
    {
        $sum = 0;

        $items = OrderItem::find()
            ->where(['order_id' => $order_id])
            ->all();

        foreach ($items as $item) {
            $product = Product::findOne(['id' => $item['product_id']]);
            $sum += $product['price_cost'] * $item['quantity'];
        }

        return $sum;
    }
    
    // 计算业绩
    private function getScore($user_id)
    {
        $all = C::getChildrenAll($user_id);
        if ($all) {
            $all = ArrayHelper::getColumn($all, 'id');
        }
        $all = array_merge([intval($user_id)], $all);
        // var_dump($all);exit;

        $orders = Order::find()
            // 不是云仓提货的
            ->where(['is_extract' => 0])
            // 团队
            ->andWhere(['user_id' => $all])
            // 上个月的
            ->andWhere("date_format(create_time,'%Y-%m')=date_format(date_sub(curdate(), interval 1 month),'%Y-%m')")
            ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
            ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
            ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
            ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
            ->select(['id', 'total_pay', 'total_freight'])
            ->asArray()
            ->all();
        // var_dump($orders);exit;

        $sum = 0;
        foreach ($orders as $order) {
            $sum += $order['total_pay'] - $order['total_freight'];
        }
        return $sum;
    }

    protected function saveCommission($user_id, $balance, $type, $name, $text = '返佣', $status = 1, $order_id = 0, $fans_id = 0)
    {
        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $fans_id;
            $model->order_id = $order_id;
            $model->balance = $balance;
            $model->status = $status;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                if ($status == 1) {
                    $account->balance += $balance;
                } else {
                    $account->await_balance += $balance;
                }
                $account->save();
            }

            // balance logs
            if ($status == 1) {
                UserBalance::addLog($model->user_id,
                    $account->balance, $model->balance, $account->balance + $model->balance, $text, $order_id);
            }

            // // 记录分红
            // $log = new MonthProfit();
            // $log->user_id = $user_id;
            // $log->amount = $user_id;
        }
    }

    protected function saveCommission2($user, $user_id, $balance, $type, $name, $text = '返佣', $status = 1)
    {
        // var_dump($user);exit;

        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = 0;
            $model->order_id = 0;
            $model->balance = $balance;
            $model->status = $status;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                if ($status == 1) {
                    $account->balance += $balance;
                } else {
                    $account->await_balance += $balance;
                }
                $account->save();
            }

            // balance logs
            if ($status == 1) {
                UserBalance::addLog($model->user_id,
                    $account->balance, $model->balance, $account->balance + $model->balance, $text, 0);
            }

            // 记录分红
            $log = new MonthProfit();
            $log->user_id = $user_id;
            $log->amount = $user['total'];
            $log->ratio = $user['ratio'];
            $log->all_commission = $user['amount'];
            $log->real_commission = $user['real_amount'];
            $log->save();
        }
    }

    // private function _profit($user, Order $order)
    // {
    //     $u = User::findOne(['id' => $user['id']]);
    //     if ($u) {
    //         $box = $this->getBox($order);
    //         // 如果按订单算, 则把盒数改成1
    //         // $box = 1;
    //
    //         // var_dump($box);exit;
    //
    //         $commission = $this->set->address_award * $box;
    //
    //         // var_dump($commission);exit;
    //
    //         // 公司出钱
    //         // $this->money += $commission;
    //
    //         $this->saveCommission($u['id'], $commission, 88, '分红', '分红', 1, $order->id, $order->user_id);
    //     }
    //
    // }

    // protected function getBox(Order $order)
    // {
    //     // 如果订单有保存盒数, 则从订单从来
    //     // if ($this->order->is_store == 1 && $this->order->store_box > 0) {
    //     //     return $this->order->store_box;
    //     // }
    //
    //     if ($order->is_store == 1 && $order->store_box > 0) {
    //         return $order->store_box;
    //     }
    //
    //     // 否则从产品中算 (可能产品有改动)
    //     $items = OrderItem::find()
    //         ->where(['order_id' => $order->id])
    //         ->with(['product'])
    //         ->all();
    //     $box = 0;
    //     foreach ($items as $item) {
    //         if ($item['product']) {
    //             $box += $item['product']['store'] * $item['quantity'];
    //         }
    //     }
    //
    //     return  $box;
    // }

    // private function isOut($user_id)
    // {
    //     $total_ids = Chain::getChildrenAllQuick($user_id, [], ['id']);
    //     $total_ids = ArrayHelper::getColumn($total_ids, 'id');
    //     $total_ids = array_merge([$user_id], $total_ids);
    //
    //     $child_svip2 = User::find()
    //         ->where(['referrer_id' => $user_id])
    //         ->andWhere(['level' => UserLevel::$keys['svip2']])
    //         ->select(['id'])
    //         ->column();
    //
    //     // var_dump($total_ids, $child_svip2);exit;
    //
    //     // 总业绩
    //     $total_box = $this->boxByOrder($total_ids);
    //     if ($total_box == 0) {
    //         return false;
    //     }
    //
    //     // var_dump($total_box);exit;
    //
    //     // 判断部门业绩
    //     foreach ($child_svip2 as $id) {
    //         $child = Chain::getChildrenAllQuick($id, [], ['id']);
    //         $child = ArrayHelper::getColumn($child, 'id');
    //         $child = array_merge([$id], $child);
    //         $box = $this->boxByOrder($child);
    //
    //         // echo $id, ' -> ', $box, ' - ';
    //         // continue;
    //
    //         // 如果部门没有业绩, 可以设置不返
    //         if ($box == 0) {
    //             return true;
    //         }
    //
    //         // 是否大于50%
    //         if ($box / $total_box >= 0.5) {
    //             return true;
    //         }
    //     }
    //
    //     // exit;
    //
    //     return false;
    // }

    // private function boxByOrder($ids)
    // {
    //     $orders = Order::find()
    //         ->where(['user_id' => $ids])
    //         ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
    //         ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
    //         ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
    //         ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
    //         // 提货的不算
    //         ->andWhere(['is_extract' => 0])
    //         ->select(['id'])
    //         ->column();
    //
    //     // var_dump($orders);exit;
    //
    //     $items = OrderItem::find()
    //         ->where(['order_id' =>$orders])
    //         ->with(['product'])
    //         ->all();
    //     $box = 0;
    //     foreach ($items as $item) {
    //         if ($item['product']) {
    //
    //             // 84000 不算
    //             if ($item['product']['price'] == 84000) {
    //                 continue;
    //             }
    //
    //             $box += $item['product']['store'] * $item['quantity'];
    //         }
    //     }
    //
    //     return  $box;
    // }
}